import React, {useEffect, useState} from "react";
import {Button, Input, Modal, Space, Table, Tag, Typography} from "antd";
import {imagesList, imagesRemove} from "@/api/docker";
import {DefaultImageDrawerProp, ImageDrawerProp, ImageListProp, ImageListQueryProp} from "@/pages/docker/modules";
import {ColumnsType} from "antd/es/table";
import {formatFileSize, is} from "@/utils/other";
import {color} from "@/utils/color";
import {ImageSearchDrawer, ImagesExport, ImagesInfo} from "@/pages/docker/components";
import {useRequest} from "ahooks";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import ImagesSetTag from "@/pages/docker/components/images.set.tag";

export const DockerImages = () => {

	const columns: ColumnsType<ImageListProp> = [
		{
			title: '镜像ID',
			key: 'id',
			dataIndex: 'id',
			align: 'center',
			ellipsis: true,
			width: 200,
			render: (text, record) => <Typography.Link onClick={() => setDrawerProp({...drawerProp, infoVisible: true, target: record})}>{text}</Typography.Link>
		},
		{
			title: '标签',
			key: 'tags',
			dataIndex: 'tags',
			align: 'center',
			render: (text, record) => <Space size={[0, 8]} wrap>
				{record.tags.map((item, index) => <Tag key={index} color={color(index)}>{item}</Tag>)}
			</Space>
		},
		{
			title: '大小',
			key: 'size',
			dataIndex: 'size',
			align: 'center',
			width: 160,
			render: (text, record) => <>{formatFileSize(record.size)}</>
		},
		{
			title: '创建时间',
			key: 'createTime',
			dataIndex: 'createTime',
			align: 'center',
			width: 160,
		},
		{
			title: '操作',
			key: 'active',
			align: 'center',
			width: 160,
			render: (text, record, index) => (
				<Space size={'small'}>
					<Button type="link" style={{padding: 4}} onClick={() =>setDrawerProp({...drawerProp, tagVisible: true, target: record})}>标签</Button>
					<Button type="link" style={{padding: 4}} onClick={() => setDrawerProp({...drawerProp, exportVisible: true, target: record})}>导出</Button>
					<Button type="link" danger style={{padding: 4}} onClick={() => deleteImage(record)}>删除</Button>
				</Space>
			),
		},
	]

	const [modal, contextHolder] = Modal.useModal();
	const [total, setTotal] = useState<number>(0);
	const [pullVisible, setPullVisible] = useState<boolean>(false);
	const [drawerProp, setDrawerProp] = useState<ImageDrawerProp>(DefaultImageDrawerProp);
	const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
	const [datasource, setDatasource] = useState<ImageListProp[]>([]);
 	const [imageQuery, setImageQuery] = useState<ImageListQueryProp>({page: 1, size: 10, isAll: false});
	const {loading, run} = useRequest(imagesList, {
		manual: true,
		onSuccess: (data)=> {
			setDatasource(data.records);
			setTotal(data.total)
		}
	})


	const loadImages = async (data: ImageListQueryProp) => {
		const {total, records} = await imagesList(data)
		setTotal(total);
		setDatasource(records);
	}

	const closeDrawer = (isLoad: boolean, types: 'pull' | 'info' | 'tag' | 'export') => {
		if (types === 'pull') {
			setPullVisible(false);
		} else if (types === 'tag') {
			setDrawerProp({...drawerProp, tagVisible: false, target: undefined});
		} else if (types === 'info') {
			setDrawerProp({...drawerProp, infoVisible: false, target: undefined});
		} else if (types === 'export') {
			setDrawerProp({...drawerProp, exportVisible: false, target: undefined});
		}
		if (isLoad) {
			run(imageQuery)
		}
	}

	const deleteImage = (target: ImageListProp) => {
		modal.confirm({
			title: '警告',
			icon: <ExclamationCircleOutlined />,
			content: '删除镜像将无法恢复，确认删除？',
			okText: '确定',
			cancelText: '取消',
			onOk: async () => {
				await imagesRemove(target.id, false);
				run(imageQuery);
			}
		});

	}

	useEffect(() => {run(imageQuery)}, [])

	return <>
		<Space>
			<Button type='primary' onClick={() => setPullVisible(true)}>拉取镜像</Button>
			<Button type='primary' onClick={() => run(imageQuery)}>刷新</Button>
			<Button type='primary'>导入镜像</Button>
			<Button type='primary'>构建镜像</Button>
			<Button type='primary' danger>清理镜像</Button>
			<Input placeholder="输入镜像名称进行搜索" allowClear />
		</Space>
		<Table
			bordered
			size={'small'}
			columns={columns}
			loading={loading}
			dataSource={datasource}
			style={{ marginTop: 10 }}
			rowKey={(record) => record.id}
			pagination={{
				onShowSizeChange: (current, size) => loadImages({...imageQuery, page: current, size: size}),
				onChange: (page, pageSize) => loadImages({...imageQuery, page: page, size: pageSize}),
				showTotal: () => `共 ${total} 个`,
				showQuickJumper: true,
				showSizeChanger: true,
				pageSize: imageQuery.size,
				current: imageQuery.page,
				size: 'default',
				total: total,
			}}
			rowSelection={{
				type: 'checkbox',
				selectedRowKeys: selectedRowKeys,
				onChange: (selectedRowKeys: React.Key[], selectedRows: ImageListProp[]) => {
					setSelectedRowKeys([...selectedRowKeys.map(item => item as string)])
				}
			}}
		/>
		<ImagesExport visible={drawerProp.exportVisible} target={drawerProp.target} close={() => closeDrawer(false, 'export')} />
		<ImagesInfo visible={drawerProp.infoVisible} imageId={drawerProp.target?.id} close={() => closeDrawer(false, 'info')} />
		<ImageSearchDrawer visible={pullVisible} close={(isLoad) => closeDrawer(isLoad, 'pull')} />
		<ImagesSetTag visible={drawerProp.tagVisible} target={drawerProp.target} close={(isLoad) => closeDrawer(isLoad, 'tag')} />
		{contextHolder}
	</>
}